<template>
  <div class="user">&nbsp;&nbsp;
    <div class="a">
      <el-popover
          :width="100"
      >
        <template #reference>
          <el-avatar :src="userURL" @click="dialogVisible = true"/>
        </template>
        <template #default>
          <div class="popover" style="cursor: pointer">
            <p>{{ user.userName }}</p>
            <el-divider/>
            <p @click="exit">退出</p>
          </div>
        </template>
      </el-popover>

      <el-dialog v-model="dialogVisible" width="500px">
        <el-upload
            class="upload-demo"
            drag
            :action="url2"
            multiple
            :on-success="definite"
        >
          <el-icon class="el-icon--upload">
            <upload-filled/>
          </el-icon>
          <div class="el-upload__text">
            将文件拖到此处或 <em>点击上传</em>
          </div>
          <template #tip>
            <div class="el-upload__tip">
              jpg/png 文件 文件大小最好不要超过500kb
            </div>
          </template>
        </el-upload>
      </el-dialog>
    </div>
  </div>
</template>

<script setup>
import {getCurrentInstance, ref, defineEmits} from "vue";
import {useRouter, useRoute} from "vue-router";
import {ElMessage} from "element-plus";

const proxy = getCurrentInstance().appContext.config.globalProperties;

const user = ref(proxy.$cookie.get('userInfo'))
const router = useRouter();  // 跳转url
const userURL = proxy.$url + '/getAvatar?fileName=' + user.value.avatarName
const url2 = proxy.$url + '/avatarUpload?userId=' + user.value.userId

const exit = () => {
  proxy.$cookie.remove("userInfo")
  proxy.$cookie.remove("token")
  router.push("/login")
}

const dialogVisible = ref(false)

const definite = () => {
  proxy.$http.get(
      proxy.$url + '/getUser',
      {
        params: {id: user.value.id},
        headers: {
          "token": proxy.$cookie.get("token")
        }
      }
  ).then(
      (response) => {
        if (response.data.code === 200) {
          proxy.$cookie.set('userInfo', response.data.data)
          dialogVisible.value = false
          // location.reload()
        } else {
          ElMessage({
            type: "error",
            message: response.data.msg,
            duration: 2000
          })
        }

      }
  )
}

</script>

<style scoped>
.user {
  width: 100px;
  position: absolute;
  right: 50px;
  top: 15px;
  display: flex;
  align-items: center;


}

.a {
  float: left;
}

.popover {
  text-align: center;
  /*line-height: 10px;*/
}

.popover a {
  text-decoration: none;
  color: #888888;
}

.headPortrait img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}


</style>
